var server = require('../server')
var db = require('../../db/connect')
var jsonres = require('../../libs/jsonres')
var request = require('request');
var config = require('../../config')
var Async = require('async');

var isJson = function(str) {
    try {
        JSON.parse(this.toString())
        return true;
    } catch(e) {
        return false;
    }
}
String.prototype.isJson = isJson;


// TODO get请求获取到指定taskid的数据,然后插入本地数据库
server.post('/api/updatetask',function(req, res) {
    var taskid = req.query.taskid;
    console.log('body:',req.body)
    var body = req.body.data;
    console.log(taskid)

    Async.waterfall([
        function(callback) {
            db.count('tasks',{taskId: taskid},function(err,count){
                if (count > 0) {
                    callback(null,true)
                } else {
                    callback(`task: '${taskid}' not found in local db!`)
                }
            })
        },
        // 检查task是否完成,接口数据是否完整 避免入库出错
        function(next,callback) {
            db.count('tasks',{taskId: taskid, finished: false},function(err,count){
                if (count > 0) {
                    request({
                        url: config.dispatcher_host + '/getanadata?taskid=' + taskid,
                        method: 'get',
                    },function(err,httpResponse,getanadataBody) {
                        if (getanadataBody.isJson()) {
                            request({
                                url: config.dispatcher_host + '/getcountdata?taskid=' + taskid,
                                method: 'get',
                            },function(err,httpResponse,getcountdataBody) {
                                if (getcountdataBody.isJson()) {
                                    return callback(null,getanadataBody,getcountdataBody)
                                } else {
                                    return callback(`task: '${taskid}' not found in getcountdata!`)
                                }
                            });
                        } else {
                            return callback(`task: '${taskid}' not found in getanadata!`)
                        }
                    });
                } else {
                    return callback(`task: '${taskid}' already updated!`)
                }
            })
        },

        function(getanadataBody,getcountdataBody, callback){
            var anaDataObje = JSON.parse(getanadataBody)
            // var newObj = [];
            anaDataObje.map(function(i) {
                i.rowid = i.Id_
                i.date = new Date(i.date)
                // newObj.push(i)
                db.insert('matchdatas',i)
            })
            
            var countDataObj = JSON.parse(getcountdataBody);
            db.update('platforms',{platform: countDataObj.platform, mobile: countDataObj.userinfo.userid},
                {
                    total: countDataObj.total,
                    inpoor: countDataObj.inpoor,
                    gains: countDataObj.gains,
                    winningRatio: countDataObj.winningratio
                },true,function(err, result) {
                    if (!!err) {
                        console.log('error')
                        return callback(`task: '${taskid}' update countdata has unkown error!`)
                    } else {
                        console.log('true')
                        return callback(null,true)
                    }
                }
            )
        },

        function(next, callback) {
            db.update('tasks',{taskId: taskid},{finished: true,rounds: body},false,function(err,result) {
                if (result.n <= 0) {
                    return callback(`task: '${taskid}' update task status has unkown error!`)
                } else {
                    return callback(null,true)
                }
            })
        }
    ],function(err, result){
        if (err) {
            console.log(err)
            return res.send(jsonres(-1,err,null))
        } else {
            return res.send(jsonres(200,'update task success!',null))
        }
    })
})